package com.sxt.pro.Ny_data.xin;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sxt.pro.pojo.InMessage;
import com.sxt.pro.pojo.OutMessage;
import com.sxt.pro.pojo.Sources;
import com.sxt.pro.service.SourcesService;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @author xinxiaokang
 * @create 2020-06-14 22:48
 * @desc WebSocketService
 * 项目名称：
 */
@Service
@Slf4j
public class WebSocketService {
	
	/**  websockegt 发送消息模板 **/
	@Autowired
	private SimpMessagingTemplate template;
	/**  素材 **/
	@Autowired
	private SourcesService sourcesService;
	
	/**
	 * 发布产品
	 */
//	@Scheduled(fixedRate = 10000)
	public void  sendTopicMessage(InMessage message) {
		template.convertAndSend("/topic/service_info",new OutMessage(message.getContent()));
	}
	
	
	/**
	 * 青岛：文化剧场:视频、图片播放提醒
	 */
//	@Scheduled(fixedRate = 10000)
	public void  sendNoticeMessage() {
		List<Map<String, Object>> data = null;
		int available = 1;  //默认已审批
		Date nowTime = null;
		Date beginTime = null;
		Date endTime = null;
		List<Sources>  sourcesDataNew= new ArrayList<Sources>();
		try {
			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			//获取当前时间
			String newDate = sdf.format(new Date());
			//转化为data模式
			nowTime = sdf.parse(newDate);
			 //获取文化剧场已经审批的素材图片和视频素材
			 QueryWrapper<Sources> queryWrapper = new QueryWrapper<Sources>();
			//筛选条件：网点编号
			  queryWrapper.eq("available",available);
		     List<Sources>  sourcesData= this.sourcesService.list(queryWrapper);
		     for (int i = 0; i < sourcesData.size(); i++) {
		    	if (sourcesData.get(i).getTimerange()!=null  ) {
		    		String beginTime1 = sourcesData.get(i).getTimerange().substring(0, sourcesData.get(i).getTimerange().indexOf("~"));
		    		String endTime1 = sourcesData.get(i).getTimerange().substring(sourcesData.get(i).getTimerange().indexOf("~")+1);
		    		beginTime=sdf.parse(beginTime1);
		    		endTime=sdf.parse(endTime1);
		    		Boolean flag = belongCalendar(nowTime, beginTime, endTime);
				  if (flag) {
					  sourcesDataNew.add(sourcesData.get(i));
				  }				
				}
			}
	         Map<String, Object> map = new HashMap<String, Object>();
	         data = new ArrayList<Map<String, Object>>();
	         if (!sourcesDataNew.isEmpty()) {
	        	 map.put("sources", sourcesDataNew);
	        	  data.add(map);
	        	 template.convertAndSend("/topic/service_Notice",new OutMessage(JSON.toJSONString(data)));
			}
		} catch (Exception e) {
			 e.printStackTrace();
		}
		 
	}
	
	
	/**
	 * 青岛：文化剧场:视频、图片播放提醒
	 */
//	@Scheduled(fixedRate = 10000)
//	public void  sendNoticeMessage() {
//		String lable = "文化剧场";  //默认删选的标签
//		List<Map<String, Object>> data = null;
//		Date nowTime = null;
//		Date beginTime = null;
//		Date endTime = null;
//		List<Images>  imagesDataNew= new ArrayList<Images>();
//		List<Videos>  videosDataNew= new ArrayList<Videos>();
//		try {
//			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			//获取当前时间
//			String newDate = sdf.format(new Date());
//			//转化为data模式
//			nowTime = sdf.parse(newDate);
//			 //获取文化剧场的图片和视频素材
//		     List<Images>  imagesData= this.imagesService.sendImageData(lable);
//		     for (int i = 0; i < imagesData.size(); i++) {
//		    	if (imagesData.get(i).getTimerange()!=null  ) {
//		    		String beginTime1 = imagesData.get(i).getTimerange().substring(0, imagesData.get(i).getTimerange().indexOf("~"));
//		    		String endTime1 = imagesData.get(i).getTimerange().substring(imagesData.get(i).getTimerange().indexOf("~")+1);
//		    		beginTime=sdf.parse(beginTime1);
//		    		endTime=sdf.parse(endTime1);
//		    		Boolean flag = belongCalendar(nowTime, beginTime, endTime);
//				  if (flag) {
//					  imagesDataNew.add(imagesData.get(i));
//				  }				
//				}
//			}
//	        List<Videos>  videosData= this.videosService.sendVideoData(lable);
//	        for (int i = 0; i < videosData.size(); i++) {
//		    	if (videosData.get(i).getTimerange()!=null  ) {
//		    		String beginTime1 = videosData.get(i).getTimerange().substring(0, videosData.get(i).getTimerange().indexOf("~"));
//		    		String endTime1 = videosData.get(i).getTimerange().substring(videosData.get(i).getTimerange().indexOf("~")+1);
//		    		beginTime=sdf.parse(beginTime1);
//		    		endTime=sdf.parse(endTime1);
//		    		Boolean flag = belongCalendar(nowTime, beginTime, endTime);
//				  if (flag) {
//					  videosDataNew.add(videosData.get(i));
//				  }				
//				}
//			}
//	         Map<String, Object> map = new HashMap<String, Object>();
//	         data = new ArrayList<Map<String, Object>>();
//	         if (!imagesDataNew.isEmpty()) {
//	        	 map.put("image", imagesDataNew);
//			}
//	         if (!videosDataNew.isEmpty()) {
//	        	 map.put("video", videosDataNew);
//			}
//	         data.add(map);
//		} catch (Exception e) {
//			 e.printStackTrace();
//		}
//		  template.convertAndSend("/topic/service_Notice",new OutMessage(JSON.toJSONString(data)));
//	}

	
	/**
	 * 判断时间是否在时间段内
	 * 
	 * @param nowTime
	 * @param beginTime
	 * @param endTime
	 * @return
	 */
	public static boolean belongCalendar(Date nowTime, Date beginTime,
			Date endTime) {
		Calendar date = Calendar.getInstance();
		date.setTime(nowTime);
 
		Calendar begin = Calendar.getInstance();
		begin.setTime(beginTime);
 
		Calendar end = Calendar.getInstance();
		end.setTime(endTime);
 
		if (date.after(begin) && date.before(end)) {
			return true;
		} else {
			return false;
		}
	}
	
	
/**         银行爬取数据                                                                          **/	
	
	//利率
	@Scheduled(fixedRate = 10*1000)
	@Scheduled(cron = "0 0 * * * ?")   //每小时执行一次
    public void  sendLilvMessage(){
        String url ="http://www.abchina.com/cn/PersonalServices/Quotation/bwbll/201511/t20151126_807920.htm";//外汇："http://ewealth.abchina.com/app/data/api/DataService/RealTimeExchangeRateV3";贵金属：//"http://ewealth.abchina.com/app/data/api/DataService/GoldInfoV2";
        String nongh = null;
        try {
            nongh = HttpClientHelper.sendGet(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = new byte[0];
        try {
            bytes = nongh.getBytes("ISO-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String s1 = null;
        try {
            s1 = new String(bytes, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Document document = Jsoup.parse(s1);
        Elements tbody = document.getElementsByTag("tbody");
        String[] split = tbody.text().split(" ");
        List<Lilv> lilvs = new ArrayList<>();
        for (int x=0;x<split.length;x++){
            Lilv lilv = new Lilv();
            if(x%2==0){
                lilv.setPriect(StringUtils.strip(split[x]));
                x++;
            }
            lilv.setData(StringUtils.strip(split[x]));
            lilvs.add(lilv);
        }

        String s = JSONObject.toJSONString(lilvs);
        template.convertAndSend("/topic/service_lilv", new OutMessage(s));
    }
//
//	//贵金属
////    @Scheduled(fixedRate = 10*1000)
////    @Scheduled(cron = "0 0 * * * ?")   //每小时执行一次
//    public void sendGoldMessage(){
//        String url ="http://ewealth.abchina.com/app/data/api/DataService/GoldInfoV2";//外汇："http://ewealth.abchina.com/app/data/api/DataService/RealTimeExchangeRateV3";贵金属：//"http://ewealth.abchina.com/app/data/api/DataService/GoldInfoV2";
//        String nongh = null;
//        try {
//            nongh = HttpClientHelper.sendGet(url);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        JSONArray array = JSONObject.parseObject(nongh).getJSONObject("Data").getJSONArray("Table1");
//        int size = array.size();
//        for (int x=0;x<size;x++){
//            String[] split = array.getJSONObject(x).get("UpdateTime").toString().split(" ");
//            //System.out.println("数组长度："+split.length);
//            array.getJSONObject(x).put("UpdateTime",split[1]);
//        }
//        //System.out.println("贵金属："+array);
//        template.convertAndSend("/topic/service_gold", new OutMessage(array.toString()));
//    }
//    
//    //汇率
////    @Scheduled(fixedRate = 10*1000)
////    @Scheduled(cron = "0 0 * * * ?")   //每小时执行一次
//    public void sendHuilv(){
//        String url ="http://ewealth.abchina.com/app/data/api/DataService/ExchangeRateV2";//外汇："http://ewealth.abchina.com/app/data/api/DataService/RealTimeExchangeRateV3";贵金属：//"http://ewealth.abchina.com/app/data/api/DataService/GoldInfoV2";
//        String nongh = null;
//        try {
//            nongh = HttpClientHelper.sendGet(url);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        JSONArray array = JSONObject.parseObject(nongh).getJSONObject("Data").getJSONArray("Table");
//        int size = array.size();
//        for (int x=0;x<size;x++){
//            String[] split = array.getJSONObject(x).get("PublishTime").toString().split("T");
//            //System.out.println("数组长度："+split[1].split("\\+")[0]);
//            array.getJSONObject(x).put("PublishTime",split[1].split("\\+")[0]);
//        }
//       // System.out.println("汇率："+array);
//        template.convertAndSend("/topic/service_exchange", new OutMessage(array.toString()));
//    }
//	
	
	

}
